var opentext = {};
// Define the custom namespace;
//
// Data Beans - static object keeping the configuration parameters for
// across the application namespace. As a static object the initial
// structure is set up at startup and can keep the data without
// calling the constructor.
//
// This strategy defines data bean inside the namepsace opentext.
// The bean can store arbitrary data and give them back to callee.
// The immediate function pattern is used to define the Bean
// Container.
opentext.beans = {};
opentext.beans.itsm = (function() {
//<<<
	var me = this;
	me.conf = {};	
	return {
		conf: this.conf,
		set: function( pars ) {
//			console.log('opentext.beans.set() called');
			opentext.tools.merge( this.conf, pars );
//			for (var i in me.conf)
//				console.log( '	' + i + ' = ' + me.conf[i] + " is of type " + typeof me.conf[i]);
		},
		get: function( n ) {
//			console.log('opentext.beans.get(' + n + ') enter');
			if( typeof conf[n] === 'undefined' ) {
				console.warn( 'opentext.beans.webviewer Bean does not contain property: ' + n ); 
				return 'undefined';
			}
//			console.log('opentext.beans.get(' + n + ') returning ' + conf[n] );
			return conf[n];	
		}
	};
}());
//>>>

// Common tools inside the application namespace.
// Used pattern - immediate function - makes sure that the
// opentext.tools is a pointer to object having an public API.
// The pattern produces a static object, accessible across the
// application namespace.
opentext.tools = (function() {
//<<<
	var me = this;
	var bean = opentext.beans.itsm;
	var a,a0;
	me.data = {};
	return {
		data: this.data,

		buildListViewNode: function( entry ) {
			var html = '<li data-theme="c" data-cust-case="';
			html += entry.case;
			html += '"><img src="';
			html += entry.icon;
			html += '" class="ui-li-icon" style="max-width: 29px; max-height: 29px; left: 6px"/><h1>';
			html += entry.description;
			html += '</h1><ul data-cust-leaf="true"><li data-theme="c">';
	 		html += '<div class="custom-header">';
			html += '<h3 class="custom-header-overlap">Details</h3></div>';
			html += '<div class="custom-details-table">';
			html += '<div class="custom-details-row">';
			html += '<div class="custom-details-cell-name">Subject:</div>';
			html += '<div class="custom-details-cell-value">';
			html += entry.description; 
			html += '</div> </div> </div> <div class="custom-details-table right"> <div class="custom-details-row"> <div class="custom-details-cell-name left">Status:</div> <div class="custom-details-cell-value left">'; 
		 	html +=  entry.status;
			html += '</div> </div> </div> <div class="custom-details-table"> <div class="custom-details-row"> <div class="custom-details-cell-name">Case:</div> <div class="custom-details-cell-value" data-cust-case="';
			html += entry.case; 
			html += '" data-cust-case-id="';
			html += entry.id; 
			html += '">'; 
			html += entry.case; 
			html += '</div> </div> </div> <div class="custom-details-table right"> <div class="custom-details-row"> <div class="custom-details-cell-name left">Jira:</div> <div class="custom-details-cell-value left">[<a href="https://jira.opentext.com/browse/';
		   html +=	entry.jira;
			html +=	'">';
		  	html += 	entry.jira;
			html += '</a>]</div> </div> </div> <div class="custom-details-table"> <div class="custom-details-row"> <div class="custom-details-cell-name">Project:</div> <div class="custom-details-cell-value">';
		   html += entry.project;
		   html += '</div> </div> </div> <div class="custom-details-table right"> <div class="custom-details-row"> <div class="custom-details-cell-name left">Created:</div> <div class="custom-details-cell-value left">';
		  	html += entry.start;
		   html += '</div> </div> </div> <div class="custom-details-table"> <div class="custom-details-row"> <div class="custom-details-cell-name">Reference:</div> <div class="custom-details-cell-value">[<a href="https://jira.opentext.com/browse/';
		   html += entry.reference;
		  	html += '">';
		   html += entry.reference;
		   html += '</a>]</div> </div> </div> <div class="custom-details-table right"> <div class="custom-details-row"> <div class="custom-details-cell-name left">Update:</div> <div class="custom-details-cell-value left">';
		   html += entry.checkpoint;
			html += '</div> </div> </div> <div class="custom-details-table"> <div class="custom-details-row"> <div class="custom-details-cell-name">Reworking:</div> <div class="custom-details-cell-value">';
		   html += entry.rework;
		  	html += '</div> </div> </div> <div class="custom-details-table right"> <div class="custom-details-row"> <div class="custom-details-cell-name left">Closed:</div> <div class="custom-details-cell-value left">';
		   html += entry.stop;
		   html += '</div> </div> </div> <div class="custom-details-table"> <div class="custom-details-row"> <div class="custom-details-cell-name">Age:</div> <div class="custom-details-cell-value">';
		   html += entry.age;
		   html += '</div> </div> </div> <div class="custom-details-table collspan"> <div class="custom-details-row"> <div class="custom-details-cell-name">Patches:</div> <div class="custom-details-cell-value">';
		   html += entry.patches;
		   html +='</div> </div> </div> <div class="collspan">&nbsp;</div> <div class="custom-header collspan"> <h3 class="custom-header-overlap">Synopsis</h3></div> <div style="font-size: 0.9em;padding-left:8px; clear: both">';
		   html += entry.synopsis;
		   html += '</div> <div class="collspan">&nbsp;</div> <div class="custom-header collspan"> <h3 class="custom-header-overlap">Chronicle</h3></div> <div style="font-size: 0.8em;padding-left:8px; clear: both">';
//						   html += entry.description;
		   html += entry.details;
		   html +='</div> </li> </ul> </li>';

			return html;
		},

		getVal: function( url, pattern ) {
			var tmp;
			console.log( 'opentext.tools.getVal() search for pattern = ' + pattern + ' in URL = ' + url );
			tmp = url.slice(url.indexOf("&") + 1);
			a = tmp.split("&");
			if( typeof a === 'object' && a.length > 0 ) {
				for( var it in a ) {
					if( typeof a[it] !== 'undefined' ) {
						a0 = a[it].split("=");
						if( a0[0] === pattern ) {
							tmp = a0[1];
							break;
						}
					}
				}
			} else {
				console.warn( 'opentext.tools.getVal(): the source is not an array. Cannot find a pattern' );
				tmp = "";
			}

			console.log( 'opentext.tools.getVal() found pattern = ' + pattern + ' = ' + tmp );
			return tmp;
		},

		encodeurl: function( str ) {
			var tmp = encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
			console.log( 'opentext.tools.encoderurl input = ' + str );
			console.log( 'opentext.tools.encoderurl result = ' + tmp );
			return tmp;
		},

		decodeHTML: function( str ) {
			var tmp = str.split("&#034;").join('"'); 
			return tmp;
		},

		merge: function(a,b) {
			console.log('opentext.tools.merge() called');
			for( var i in b )
				if(b[i] !== undefined)
					a[i] = b[i];
		},

		notificationDestroy: function() {
			var vc = document.getElementById( bean.get( 'wall' ) );
			var o = document.getElementById( 'notification_box' );
			vc.removeChild( o );
		},

		notification: function( txt, style, time ) {
			var vc = document.getElementById( bean.get( 'wall' ) );
			var nim = document.createElement('div');
			nim.setAttribute('id', 'notification_box' );
//			nim.setAttribute('class', 'loading loading_blue' );
			nim.setAttribute('class', style );
			nim.innerHTML = txt;
			vc.appendChild( nim );
			setTimeout( 'opentext.tools.notificationDestroy()', time );
		},

		getBrowserDimension: function () {
			var dimension = { pageWidth: 0, pageHeight: 0, windowWidth: 0, windowHeight: 0 };

			if (window.innerHeight && window.scrollMaxY) {  
				dimension.pageWidth = document.body.scrollWidth;
				dimension.pageHeight = window.innerHeight + window.scrollMaxY;
			} 
			else if (document.body) {
				if (document.body.scrollHeight > document.body.offsetHeight) {
					dimension.pageWidth = document.body.scrollWidth;
					dimension.pageHeight = document.body.scrollHeight;
				} 
				else {
					dimension.pageWidth = document.body.offsetWidth;
					dimension.pageHeight = document.body.offsetHeight;
				}
			}

			if (window.innerHeight) {
				dimension.windowWidth = window.innerWidth;
				dimension.windowHeight = window.innerHeight;
			} 
			else if (document.documentElement && document.documentElement.clientHeight) {
				dimension.windowWidth = document.documentElement.clientWidth;
				dimension.windowHeight = document.documentElement.clientHeight;
			} 
			else if (document.body) {
				dimension.windowWidth = document.body.clientWidth;
				dimension.windowHeight = document.body.clientHeight;
			}         

			if (dimension.pageWidth < dimension.windowWidth) dimension.pageWidth = dimension.windowWidth;
			if (dimension.pageHeight < dimension.windowHeight) dimension.pageHeight = dimension.windowHeight;

			return dimension;
		}
	};
}());
//>>>


opentext.controller = (function() {
//<<<
	// Provate data and methods.
	var me = this;
	var bean = opentext.beans.itsm;
	me.data = { 'version':'1.0' };
	return {
		data: this.data,

		onFooterDetailCard: function( event, ui ) {
			// <<<
			var myFooterTempl = ' \
			<div data-role="footer" data-position="fixed" data-theme="b" class="ui-footer ui-bar-b ui-footer-fixed slideup" role="contentinfo"> \
				<span class="right"> \
				  	<a href="#page_mail" id="page_mail_btn" data-role="button" data-icon="cust-mail" data-inline="true">Mail</a> \
				  	<a href="#" data-role="button" data-icon="star" data-inline="true">Favs</a> \
				  	<a href="#" data-role="button" data-icon="bars" data-inline="true">Actions</a> \
				  	<a href="#" data-role="button" data-icon="cust-link" data-inline="true">Links</a> \
				  	<a href="#page_edit_case" data-role="button" data-icon="edit" data-inline="true">Edit</a> \
				</span> \
			</div>';
			//
//			var myFooterTempl = '<div data-role="footer" data-position="fixed" data-theme="b" class="ui-footer ui-bar-b ui-footer-fixed slideup" role="contentinfo"> <h1 class="ui-title" role="heading" aria-level="1">&nbsp</h1> <a href="#" data-role="button" data-icon="bars" class="ui-btn-right ui-btn ui-btn-up-b ui-shadow ui-btn-corner-all ui-btn-icon-left" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-theme="b"><span class="ui-btn-inner"><span class="ui-btn-text">Done</span><span class="ui-icon ui-icon-bars ui-icon-shadow">&nbsp;</span></span></a> </div>';


			// If the previous page length is zero then we couldn't possibly be drilling into a nested list this very moment
			if (ui.prevPage.length == 0) return;
		
			var pathname = window.location.pathname;
			var fullPath = $(location).attr('href');
			//alert (pathname +" versus1 "+fullPath);

			var tmpA = fullPath.split('#');

			var myFooterStr = '';
			var myContentStr = '';

			var patternStr = ( bean.get('detailCardName') !== 'undefined' ? bean.get('detailCardName') : 'page2_0&ui-page' );

			if(( tmpA.length > 1 ) && ( tmpA[1].search(patternStr) > -1 )) {
				myFooterStr = ':jqmData(url="' + tmpA[1] + '") :jqmData(role="footer")';
				myContentStr = ':jqmData(url="' + tmpA[1] + '") :jqmData(role="content") :jqmData(cust-leaf="true")';
				console.log( 'searching for footer=' + myFooterStr );
			} else {
				console.warn('cannot find any page that needs my footer. Bailing out');
				return;
			}

			var myFooter = $(myFooterStr);
			if( myFooter.length > 0 ) {
				console.log('this page got already a footer, bailing out');
				return;
			} 

			myFooter = $(myContentStr);
			if( myFooter.length > 0 ) {
				console.log( 'this is the detail card, have add the right footer' );
				event.target.innerHTML = event.target.innerHTML + myFooterTempl;
			} else {
				console.log( 'Page look righ, has no footer yet but is not the detail card, so no need to add footer here' );
			}

			$(':jqmData(url="' + tmpA[1] + '")').trigger('create');
		},
		// >>>


		onFooterMailBody: function( event, ui ) {
			// <<<
			var myFooterTempl = ' \
			<div data-role="footer" data-position="fixed" data-theme="b" class="ui-footer ui-bar-b ui-footer-fixed slideup" role="contentinfo"> \
				<span class="right"> \
				  	<a href="#" data-role="button" data-icon="bars" data-inline="true">Actions</a> \
				</span> \
			</div>';
			//
//			var myFooterTempl = '<div data-role="footer" data-position="fixed" data-theme="b" class="ui-footer ui-bar-b ui-footer-fixed slideup" role="contentinfo"> <h1 class="ui-title" role="heading" aria-level="1">&nbsp</h1> <a href="#" data-role="button" data-icon="bars" class="ui-btn-right ui-btn ui-btn-up-b ui-shadow ui-btn-corner-all ui-btn-icon-left" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-theme="b"><span class="ui-btn-inner"><span class="ui-btn-text">Done</span><span class="ui-icon ui-icon-bars ui-icon-shadow">&nbsp;</span></span></a> </div>';


			// If the previous page length is zero then we couldn't possibly be drilling into a nested list this very moment
			if (ui.prevPage.length == 0) return;
		
			var pathname = window.location.pathname;
			var fullPath = $(location).attr('href');
			//alert (pathname +" versus1 "+fullPath);

			var tmpA = fullPath.split('#');

			var myFooterStr = '';

			var patternStr = ( bean.get('detailCardName') !== 'undefined' ? bean.get('detailCardName') : 'page_mail&ui-page' );

			if(( tmpA.length > 1 ) && ( tmpA[1].search(patternStr) > -1 )) {
				myFooterStr = ':jqmData(url="' + tmpA[1] + '") :jqmData(role="footer")';
				console.log( 'searching for footer=' + myFooterStr );
			} else {
				console.warn('cannot find any page that needs my footer. Bailing out');
				return;
			}

			var myFooter = $(myFooterStr);
			if( myFooter.length > 0 ) {
				console.log('this page got already a footer, bailing out');
				return;
			} 

			event.target.innerHTML = event.target.innerHTML + myFooterTempl;
			console.log('OK, you need to add footer, there is none found');

			$(':jqmData(url="' + tmpA[1] + '")').trigger('create');
		},
		// >>>


		onBuildDashboard: function() {
		// <<<
			console.log('Construct the first page dynamicaly.');
			var requestData = {'cmd':'describe_ex','data':{"context":"all","daysBack":"0","author":"all"}};
			var addr = ( bean.get('host') !== 'undefined' ? bean.get('host') : 'http://localhost/otcs/rest' ); 
			$.getJSON( addr, requestData, function(data) {
				console.log(data);
				opentext.view.drawDashbboard( data );
			});
		},
		// >>>
		/* Register the click and tap events for the dynamically created list.
		 * The poor design point is the event registration code. We need to many
		 * static registration how many the items in the list comes. That needs 
		 * to be re-worked for the dynamic mechanism.
		 */

		onCheckBackButton: function() {
		// <<<
			console.log('event "pagebeforecreate" fired');
    		var obj = $(this).filter(':jqmData(url*="ui-page")').find(':jqmData(role="header")')
    		$(this).filter(':jqmData(url*="ui-page")').find(':jqmData(role="header")').each( function() {
				$(this).prepend('<a href="#" data-role="button" data-rel="back" data-icon="back">Back</a>')
			});
  		},
		// >>>
		/* Adds dynamically Back button to each page egenerated by jQuery Mobile.
		 * TODO - is not used today because the global configuration of jQM has
		 * been used instead
		 */

		onPageShow: function(e) {
		// <<<
			var requestData = {'cmd':'send','data':{"dataName":"WebViewer","daysBack":"0","author":"all"}};
			requestData.data.dataName = (bean.get( 'dataName' ) !== 'undefined' ? bean.get('dataName') : 'WebViewer');
			var addr = ( bean.get('host') !== 'undefined' ? bean.get('host') : 'http://localhost/otcs/rest' ); 
			$.mobile.loading( 'show' );
			$.getJSON( addr, requestData, function(data) {
				console.log(data);
				opentext.view.drawPage( data, requestData.data.dataName );
			});
		},
		// >>>
		/* This function retrieves fresh data each time the listview gets 
		 * redrawn. Data is retrieved and the view is updated. 
		 */

		onMailShow: function(e,ui) {
		// <<<
			var requestData = {'cmd':'mdb_retrieve_emails','data':{"caseNo":"1"}};
			var myCase = $(':jqmData(url="' + ui.prevPage.jqmData('url') + '") div[data-cust-case]').jqmData('cust-case');
			var myCaseId = $(':jqmData(url="' + ui.prevPage.jqmData('url') + '") div[data-cust-case-id]').jqmData('cust-case-id');
			if( (typeof myCase === 'number') && (myCase > 0) ) {
				console.log( 'opentext.controller.onMailShow called for case: ' + myCase );
				requestData.data.caseNo=myCase;
				requestData.data.caseId=myCaseId;
				$.mobile.loading( 'show' );
				var addr = ( bean.get('host') !== 'undefined' ? bean.get('host') : 'http://localhost/otcs/rest' ); 
				$.getJSON( addr, requestData, function(data) {
					console.log(data);
					opentext.view.drawMailPage( data, myCase );
				});
			}
			else {
				console.error( 'opentext.controller.onMailShow: error - failed to retrieve the case number for the selected item' );
			}
		},
		// >>>

		
		onCaseEditShow: function(e,ui) {
		// <<<
			var myCase = $(':jqmData(url="' + ui.prevPage.jqmData('url') + '") div[data-cust-case]').jqmData('cust-case');
			var myCaseId = $(':jqmData(url="' + ui.prevPage.jqmData('url') + '") div[data-cust-case-id]').jqmData('cust-case-id');
			if( (typeof myCase === 'number') && (myCase > 0) ) {
				console.log( 'opentext.controller.onCaseEditShow called for case: ' + myCase );
				bean.set({'caseNo':myCase});
				bean.set({'caseId':myCaseId});
			}
			else {
				console.error( 'opentext.controller.onCaseEditShow: error - failed to retrieve the case number for the selected item' );
			}
		},
		// >>>


		onCaseEditSave: function( e, ui ) {
		// <<<
			console.log('opentext.controller.onCaseEditSave buttin clicked' );
			var requestData = {'cmd':'save_ex','data':{"caseNo":"1"}};
			var update = $('#case_edit_update').val();
			var includeSyn = $('#case_edit_include_synopsis')[0].selectedIndex;
			var synopsis = $('#case_edit_synopsis').val();
			requestData.data.caseNo=bean.get('caseNo');
			requestData.data.caseId=bean.get('caseId');
			requestData.data.caseTxt=update;
			requestData.data.flagSynopsis=includeSyn;
			requestData.data.caseSynopsis=synopsis;

			var addr = ( bean.get('host') !== 'undefined' ? bean.get('host') : 'http://localhost/otcs/rest' ); 
			$.getJSON(addr, requestData, function(data) {
				console.log(data);
				if( parseInt( data.support_data.feed.entries.code, 10 ) === 200 ) {
					$('#page_case_edit_status_message').empty();
					$('#page_case_edit_status_message').append($('<p>Update saved!</p>'));
//					$.mobile.changePage( '#page2_0', 'slide', 'true', 'false' );
					history.back();
				} else {
					$('#page_case_edit_status_message').empty();
					$('#page_case_edit_status_message').append($('<h1>Update failed!</h1>'));
				}
			});
		} 
		// >>>

	};
}());
// >>>


opentext.view = (function() {
// <<<
	var me = this;
	var bean = opentext.beans.itsm;
	me.data = { 'version':'1.0' };

	return {
		drawDashbboard: function( obj ) {
		// <<<
			var bean = opentext.beans.itsm;
			var tmpCont = {};
			var tmpArr = [];
			console.log( 'Goto data for drawing the Dashboard' + obj );
			var html = '<ul data-theme="c" data-role="listview" id="dashboard" data-inset="true">';
			if( obj.responseStatus == 200 ) {
				$.each(obj.support_data.feed.entries, function(entryIndex, entry) {
					if( typeof tmpCont[entry.category] === 'undefined' ) {
						tmpCont[entry.category]=[];
						tmpArr.push(entry.category);
					}
					tmpCont[entry.category].push(entry);
				});

				$.each(tmpArr, function(entryIndex, entry) {
					html += '<li data-role="list-divider" data-divider-theme="b">';
					html += entry;
					html += '</li>';
					$.each(tmpCont[entry], function(entryIndex, entry) {
						html += '<li><a href="#" id="cust-dashboard-entry" data-cust-code="';
						html += entry.code;
						html += '"><img src="';
						html += entry.icon;
						html += '" class="ui-li-icon" style="max-width: 29px; max-height: 29px; left: 6px; top: 6px;"/>';
						html += entry.title;
						html += '</a></li>';
					});
				});

				html += '</ul>';

				// Dynamically build the listview.
				$('#view-container-dashboard').empty();
				$('#view-container-dashboard').append($(html));
				$('#view-container-dashboard').trigger('create');

				// Adding handler to all generated items in the dynamically constructed
				// listview. Each link shows page2 with different data set. It does not
				// work for nested views so far.
				var myButtons = $('#page1 a#cust-dashboard-entry');
				$.each( myButtons, function(entryIndex, entry) {
					$(entry).bind('click', function(ev) {
						$.each( ev.target.attributes, function(eIndex, e) {
							if( e.name === 'data-cust-code' ) {
								bean.set( {'dataName': e.value });
								$.mobile.changePage( '#page2_0', 'slide', 'true', 'false' );
								console.log('Found data for this Button ');
							} else {
								console.log( 'searching for cust-data but found:' + e.name );
							}
						});
					});
				});

			} else {
				console.error('Cannot parse retrived data');
			}
		},
		// >>>

		drawPage: function( data, title ) {
		// <<<
			var html = '<ul data-role="listview" data-theme="c">';
			if( data.responseStatus == 200 ) {
				$.each(data.support_data.feed.entries, function(entryIndex, entry) {
					if( typeof entry.support_data === 'object' && typeof entry.support_data.feed.entries === 'object' ) { //OK, we have another embedded level ...
						html += '<li data-theme="c""><img src="';
						html += entry.icon;
						html += '" class="ui-li-icon" style="max-width: 29px; max-height: 29px; left: 6px"/><h1>';
						html += entry.description;
						html += '</h1><ul>';
						$.each( entry.support_data.feed.entries, function(idx, e) {
							if( typeof e.support_data === 'object' && typeof e.support_data.feed.entries === 'object' ) { //OK, we have another embedded level ...
								html += '<li data-theme="c""><img src="';
								html += e.icon;
								html += '" class="ui-li-icon" style="max-width: 29px; max-height: 29px; left: 6px"/><h1>';
								html += e.description;
								html += '</h1><ul>';
								$.each( e.support_data.feed.entries, function(idx0, e0) {
									if( typeof e0.support_data === 'object' && typeof e0.support_data.feed.entries === 'object' ) { //OK, we have another embedded level ...
										html += '<li data-theme="c""><img src="';
										html += e0.icon;
										html += '" class="ui-li-icon" style="max-width: 29px; max-height: 29px; left: 6px"/><h1>';
										html += e0.description;
										html += '</h1><ul>';
										$.each( e0.support_data.feed.entries, function(idx0, e1) {
											html += opentext.tools.buildListViewNode( e1 );
										});
										html += '</ul></li>';
									} else {
										html += opentext.tools.buildListViewNode( e0 );
									}
								});
								html += '</ul></li>';
							} else {
								html += opentext.tools.buildListViewNode( e );
							}
						});
						html += '</ul></li>';
					} else {
						html += opentext.tools.buildListViewNode( entry );
					}
				});

				html += '</ul>';
				$('#nested-view-container-0').empty();
				$('#nested-view-container-0').append($(html));
				$('#nested-view-container-0').trigger('create');


				/* Alternate method creating rebuilding the listview.
				$('#webviewer').listview( "refresh", true ); // rebuild the main list listview ...
				var lviews = $('#page2_0 :jqmData(cust-name="webviewer_gen")');
				$.each( lviews, function(entryIndex, entry) {
					console.log( typeof lviews );
					$(entry).listview(); // rebuild the listview ...
				});
				*/

				$('#page2_0 :jqmData(role="header") h1').html( title ); // Set the label of the page ...

				$.mobile.loading( 'hide' );

			} else {
				console.error('Cannot parse retrived data');
			}
		},
		// >>>
		
		drawMailPage: function( data, title ) {
		// <<<
			console.log( 'opentext.view.drawMailPage' );
			var html = '<ul data-role="listview" data-theme="c">';
			if( data.responseStatus == 200 ) {
				$.each(data.support_data.feed.entries, function(entryIndex, entry) {
					html += '<li><a href="#">';
					html += '<img src="';
					html += entry.icon;
					html += '" class="ui-li-icon" style="max-width: 29px; max-height: 29px; left: 6px; top: 14px;"/>';
					html += entry.mailSender;
					html += '<span style="font-size: 0.8em">&nbsp;(';
					html += entry.sentOn;
					html += ')</span></br><span style="font-weight: normal">';
					html += entry.mailSubject;
					html += '</span></a><ul><li>';
					html += entry.mailHTMLBody;
					html += '</li></ul></li>';
				});

				html += '</ul>';
				$('#view-container-mail').empty();
				$('#view-container-mail').append($(html));
				$('#view-container-mail').trigger('create');

				/* Alternate method creating rebuilding the listview.
				$('#webviewer').listview( "refresh", true ); // rebuild the main list listview ...
				var lviews = $('#page2_0 :jqmData(cust-name="webviewer_gen")');
				$.each( lviews, function(entryIndex, entry) {
					console.log( typeof lviews );
					$(entry).listview(); // rebuild the listview ...
				});
				*/

//				$('#page2_0 :jqmData(role="header") h1').html( title ); // Set the label of the page ...
				$.mobile.loading( 'hide' );
			} else {
				console.error('Cannot parse retrived data');
			}
		}
		// >>>
	};
}());
// >>>


// Application constructor
opentext.itsm = function(opts){
//		  <<<
	var me = this;
	var tools = opentext.tools;
	var dm = opentext.tools.getBrowserDimension();

	me.data = {
		cfg : {
			"host": "http://localhost/otcs/rest"
		},
		UI: {
// <<<
			"elementCount": "2",
			"buttons": [
						{
							"strClass": 'toolbar-item toolbar-item-hover',
							"src": 'img/rback.png',
							"alt": "Previous page",
							"width": "64",
							"height": "64", 
							"onclick": 'opentext.WebViewer.UI.changePage( \"prev\" )'
						},
						{
							'strClass':  'toolbar-item toolbar-item-hover',
							'src': 'img/rforward.png',
							'alt': 'Next Page' ,
							'width': "64",
							'height':  "64",
							'onclick':  'opentext.WebViewer.UI.changePage( \"next\" )'
						}
				]
		}
	};
// >>>

	try {
		opentext.tools.merge(me.data.cfg, opts);
		opentext.beans.itsm.set( me.data.cfg );
	} catch( e ) {
			alert( e.name + ": " + e.message );
			throw( { name: 'opentext.itsm.constructor', message: e.message } );
	}
};
// >>>


opentext.itsm.prototype = {

	run: function() {
			$(document).bind('pagebeforeshow', opentext.controller.onFooterDetailCard );
			$(document).bind('pagebeforeshow', opentext.controller.onFooterMailBody );
			$(document).delegate('#page1', 'pagecreate', opentext.controller.onBuildDashboard );
			
			$(':jqmData(url="page1")').on('--pagebeforecreate--', opentext.controller.onCheckBackButton );
			/* TODO - thios is blocked now. It is an attempt to add back button
			 * to every page that gets generated. It was resolved by configuring
			 * the jQuery framework before leading the jQuery mobile library.
			 */

			$(document).delegate('#page2_0', 'pageshow', opentext.controller.onPageShow );
			/* This is the only way I found that works for page specific event 
			 * triggered for page specific div. pagebeforecreate is trigerred
			 * just once, when the page get generated. This may be reworked for 
			 * another event (pageshow), so that the page gets refreshed every
			 * time it is shown.
			 */

			$(document).delegate('#page_mail', 'pageshow', opentext.controller.onMailShow );
			$(document).delegate('#page_edit_case', 'pageshow', opentext.controller.onCaseEditShow );
			
			$(document).delegate('#submit_case_edit_form' ,'click', opentext.controller.onCaseEditSave );
	}
};
// >>>
